import 'package:meco/common/models/browse_record_model.dart';
import 'package:meco/common/data/services/database_service.dart';
import 'package:meco/common/models/user_model.dart';
import 'package:meco/common/data/repositories/user_repository.dart';

class BrowseRecordRepository {
  final DatabaseService _databaseService = DatabaseService();
  final UserRepository _userRepository = UserRepository();
  final String _tableName = 'browse_records';

  // 添加浏览记录
  Future<int> addBrowseRecord(BrowseRecord record) async {
    final db = await _databaseService.database;
    final now = DateTime.now().millisecondsSinceEpoch;

    final recordMap = record.toJson();
    recordMap['created_at'] = now;
    recordMap['updated_at'] = now;

    try {
      return await db.insert(_tableName, recordMap);
    } catch (e) {
      print('添加浏览记录失败: $e');
      return -1;
    }
  }

  // 获取用户的所有浏览记录
  Future<List<BrowseRecord>> getUserBrowseRecords(int userId) async {
    final db = await _databaseService.database;

    try {
      final List<Map<String, dynamic>> maps = await db.query(
        _tableName,
        where: 'user_id = ?',
        whereArgs: [userId],
        orderBy: 'browse_time DESC',
      );

      if (maps.isEmpty) {
        return [];
      }

      return List.generate(maps.length, (i) {
        try {
          return BrowseRecord.fromJson(maps[i]);
        } catch (e) {
          print('解析浏览记录失败: $e');
          // 返回一个默认值，避免整个列表生成失败
          return BrowseRecord(
            userId: userId,
            contentId: 0,
            type: BrowseType.officialContent,
            browseTime: DateTime.now(),
          );
        }
      });
    } catch (e) {
      print('获取用户浏览记录失败: $e');
      return [];
    }
  }

  // 获取特定类型的浏览记录
  Future<List<BrowseRecord>> getBrowseRecordsByType(
    int userId,
    BrowseType type,
  ) async {
    final db = await _databaseService.database;

    try {
      final List<Map<String, dynamic>> maps = await db.query(
        _tableName,
        where: 'user_id = ? AND type = ?',
        whereArgs: [userId, type.index],
        orderBy: 'browse_time DESC',
      );

      if (maps.isEmpty) {
        return [];
      }

      return List.generate(maps.length, (i) {
        try {
          return BrowseRecord.fromJson(maps[i]);
        } catch (e) {
          print('解析浏览记录失败: $e');
          return BrowseRecord(
            userId: userId,
            contentId: 0,
            type: type,
            browseTime: DateTime.now(),
          );
        }
      });
    } catch (e) {
      print('获取特定类型浏览记录失败: $e');
      return [];
    }
  }

  // 删除浏览记录
  Future<bool> deleteBrowseRecord(int id) async {
    final db = await _databaseService.database;

    try {
      final result = await db.delete(
        _tableName,
        where: 'id = ?',
        whereArgs: [id],
      );
      return result > 0;
    } catch (e) {
      print('删除浏览记录失败: $e');
      return false;
    }
  }

  // 清除用户所有浏览记录
  Future<bool> clearUserBrowseRecords(int userId) async {
    final db = await _databaseService.database;

    try {
      final result = await db.delete(
        _tableName,
        where: 'user_id = ?',
        whereArgs: [userId],
      );
      return result > 0;
    } catch (e) {
      print('清除用户浏览记录失败: $e');
      return false;
    }
  }

  // 获取用户最近浏览的内容ID列表（按类型）
  Future<List<int>> getRecentBrowsedContentIds(
    int userId,
    BrowseType type, {
    int limit = 10,
  }) async {
    final db = await _databaseService.database;

    try {
      final List<Map<String, dynamic>> maps = await db.query(
        _tableName,
        columns: ['content_id'],
        where: 'user_id = ? AND type = ?',
        whereArgs: [userId, type.index],
        orderBy: 'browse_time DESC',
        groupBy: 'content_id',
        limit: limit,
      );

      if (maps.isEmpty) {
        return [];
      }

      return List.generate(maps.length, (i) => maps[i]['content_id'] as int);
    } catch (e) {
      print('获取最近浏览内容ID失败: $e');
      return [];
    }
  }

  // 获取浏览过特定内容的用户
  Future<List<User>> getViewedUsersByContent(
    int contentId,
    BrowseType type, {
    int limit = 5,
  }) async {
    final db = await _databaseService.database;

    try {
      // 获取浏览记录
      final List<Map<String, dynamic>> records = await db.rawQuery(
        '''
        SELECT DISTINCT user_id 
        FROM browse_records 
        WHERE content_id = ? AND type = ? 
        ORDER BY browse_time DESC
        LIMIT ?
      ''',
        [contentId, type.index, limit],
      );

      if (records.isEmpty) {
        return [];
      }

      // 获取用户信息
      final userIds = records.map((r) => r['user_id'] as int).toList();
      final List<User> users = [];

      for (var userId in userIds) {
        final user = await _userRepository.getUserById(userId);
        if (user != null) {
          users.add(user);
        }
      }

      return users;
    } catch (e) {
      print('获取浏览用户失败: $e');
      return [];
    }
  }
}
